//
//  fileIO.m
//  Gradekeeper0.2
//
//  Created by Lily Wang on 11/2/09.
//  Copyright 2009 i5. All rights reserved.
// 
//  Reference: http://www.servin.com/iphone/iPhone-File-IO.html

#import "fileIO.h"


@implementation fileIO

//Calls getFilePath and writes the content to the file
+ (void) writeToFile: (NSString *) fname: (NSString *)fcontent{
	NSString *path = [fileIO getFilePath: fname];
	[fcontent writeToFile:path
			  atomically:YES
		      encoding:NSStringEncodingConversionAllowLossy 
			  error:nil];
} //writeToFile

//Calls getFilePath and reads the content of the file and return it as string
+ (NSString *) readFromFile:  (NSString *) fname{
	NSString *path = [fileIO getFilePath: fname];
	NSString *fileContents = [NSString stringWithContentsOfFile:path
							  encoding:NSUTF8StringEncoding
							  error:nil];
	return fileContents;
	
} //readFromFile

//Gets the full file path of the file
+ (NSString *) getFilePath: (NSString *) fileName{
	NSArray *arrayPaths = 
	NSSearchPathForDirectoriesInDomains(
										NSDocumentDirectory,
										NSUserDomainMask,
										YES);
	
	NSString *docDir = [arrayPaths objectAtIndex:0];
	
	NSString *fname = [NSString stringWithFormat:@"/%@.txt", fileName];
	NSString *filePath = [docDir stringByAppendingString:fname];
	return filePath;	
} //getFilePath

//Checks if file exist by checking if a text file of the same name has already been created
//If the file does not exist, readFromFile will return NULL
+ (BOOL) fileExist: (NSString *) fName{
	if ([fileIO readFromFile:fName] == NULL){
		return NO;
	} else {
		return YES;
	}	
} //fileExist

//Append new username to the profileManager.txt 
+ (void) appendToFile: (NSString *) fName: (NSString *) appendContent{
	NSString *tempContent = [fileIO readFromFile:fName];
	NSString *toWrite = [NSString stringWithFormat:@"%@:%@", tempContent, appendContent];
	[fileIO writeToFile:fName:toWrite];
} //apendToFile

//Delete specified content from file, including any delimiter added to separate the content
//ex. profileManager.txt - :hello:myname
//[fileIO deleteFromFile:@"profileManager":@"hello":@":"] results in profileManger.txt - :myname
+ (void) deleteFromFile: (NSString *) fName: (NSString *) deleteContent :(NSString *) delimiter{
	NSString *tempContent = [fileIO readFromFile:fName];
	NSString *toDelete = [NSString stringWithFormat:@"%@%@",delimiter,deleteContent];
	NSString *resultContent = [tempContent stringByReplacingOccurrencesOfString:toDelete withString:@""];
	[fileIO writeToFile:fName:resultContent];
	
} //deleteFromFile

@end

